import 'package:flutter/cupertino.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:yt_devops/components/gaps.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/components/yt_text_style.dart';
import 'package:yt_devops/pages/devices/device_list/device_list_model.dart';
import 'package:yt_devops/pages/devices/device_list/device_widget.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/styles/styles.dart';
import 'package:yt_devops/utils/enums.dart';

/**
 *
 * @Description TODO
 * @Author liuer
 * @CreateTime 2024年04月01日 09:18
 */
class TabViewItemWidget extends StatelessWidget {
  final Map<String, dynamic> map;
  final bool isAll;
  final Function(DeviceListModel) onItemTaped;
  const TabViewItemWidget(
    this.map,
    this.isAll, {
    required this.onItemTaped,
    super.key,
  });

  @override
  Widget build(BuildContext context) {
    String typeId = '';
    if (map['classType'] != null) {
      typeId = map['classType'].toString();
    }
    Widget widget = const SizedBox();
    if (typeId == '1') {
      widget = _emsWidget(map);
    }
    if (typeId == '2') {
      widget = _esInverter(map);
    }
    if (typeId == '3') {
      widget = _battery(map);
    }
    if (typeId == '4') {
      widget = _inverter(map);
    }
    if (typeId == '5') {
      widget = _chargingStation(map);
    }
    if (typeId == '6') {
      widget = _snAndAlarmWidget(map);
    }
    if (typeId == '7') {
      widget = _chargePileWidget(map);
    }
    if (typeId == '8') {
      widget = _electricityMeterWidget(map);
    }
    var model = DeviceListModel.fromJson(map);
    // Log.d('typeId==' + map['classType'].toString());
    return !isAll
        ? GestureDetector(
            child: Container(
              padding: EdgeInsets.fromLTRB(16.w, 0, 16.w, 12),
              margin: EdgeInsets.fromLTRB(16.w, 10, 16.w, 0),
              decoration: BoxDecoration(
                  color: Colour.white, borderRadius: BorderRadius.circular(10)),
              child: widget,
            ),
            onTap: () {
              if (onItemTaped != null) {
                onItemTaped(model);
              }
              //   AlarmUtil.fromModule = AlarmFromWhereType.device.value;
              //   Log.d("==== 站点内Tab设备管理模块进入设备模块，值为 ${device.deviceId!} ====");
              //   NavigateUtils.toDeviceDetail(
              //     device.deviceId!,
              //     device.productType!,
              //     device.name ?? '',
              //     device.connectStatus!,
              //     productId: device.productId,
              //   );
            })
        : DeviceWidget(
            model,
            onItemTaped: (model) {
              onItemTaped(model);
            },
            isRealTime: false,
          );
    ;
  }

  ///EMS
  _emsWidget(map) {
    return Column(
      children: [
        _snAndAlarmWidget(map),
        _rowItem(
            ResKey.deviceSystemWorkMode.tr,
            map['systemOperatingModeName'] != null
                ? map['systemOperatingModeName'].toString()
                : '--'),
      ],
    );
  }

  ///储能变流器
  _esInverter(map) {
    return Column(
      children: [
        _snAndAlarmWidget(map),
        _rowItem(
            'siteMonitor.workingCondition'.tr,
            map['workStatusName'] != null
                ? map['workStatusName'].toString()
                : '--'),
        _rowItem(
            ResKey.ratedPower.tr,
            map['energyStoragePower'] != null
                ? map['energyStoragePower'].toString()
                : '--'),
        _rowItem('siteMonitor.currentPower'.tr,
            map['power'] != null ? map['power'].toString() : '--'),
      ],
    );
  }

  ///电池
  _battery(map) {
    // 0 静置 1 放电 2 充电
    var chargingAndDischargingStatus = '--';
    if (map['chargingAndDischargingStatus'].toString() == '0') {
      chargingAndDischargingStatus = ResKey.deviceStanding.tr;
    } else if (map['chargingAndDischargingStatus'].toString() == '1') {
      chargingAndDischargingStatus = ResKey.discharge.tr;
    } else if (map['chargingAndDischargingStatus'].toString() == '2') {
      chargingAndDischargingStatus = ResKey.charge.tr;
    }

    return Column(
      children: [
        _snAndAlarmWidget(map),
        _rowItem('siteMonitor.chargingAndDischargingStatus'.tr,
            chargingAndDischargingStatus),
        _rowItem(
            ResKey.ratedCapacity.tr,
            map['ratedCapacity'] != null
                ? map['ratedCapacity'].toString()
                : '--'),
        _rowItem(
            ResKey.currentSoc.tr, map['soc'] != null ? '${map['soc']}%' : '--'),
      ],
    );
  }

  ///逆变器
  _inverter(map) {
    return Column(
      children: [
        _snAndAlarmWidget(map),
        _rowItem(
            'siteMonitor.numberGeneratingSets'.tr,
            map['generatingElectricityPv'] != null
                ? map['generatingElectricityPv'].toString()
                : '--'),
        _rowItem(
            ResKey.runningState.tr,
            map['runningState'] != null
                ? map['runningState'].toString()
                : '--'),
        _rowItem(
            ResKey.totalStringCapacity.tr,
            map['totalCapacityOfComponents'] != null
                ? map['totalCapacityOfComponents'].toString()
                : '--'),
        _rowItem(
            ResKey.ratedPower.tr,
            map['energyStoragePower'] != null
                ? map['energyStoragePower'].toString()
                : '--'),
        _rowItem('siteMonitor.currentPower'.tr,
            map['power'] != null ? map['power'].toString() : '--'),
      ],
    );
  }

  ///充电桩
  _chargingStation(map) {
    return Column(
      children: [
        _snAndAlarmWidget(map),
        _rowItem(
            ResKey.totalStringCapacity.tr,
            map['generatingElectricityPv'] != null
                ? map['generatingElectricityPv'].toString()
                : '--'),
        _rowItem(
            ResKey.ratedPower.tr,
            map['energyStoragePower'] != null
                ? map['energyStoragePower'].toString()
                : '--'),
        _rowItem('siteMonitor.currentPower'.tr,
            map['power'] != null ? map['power'].toString() : '--'),
        _rowItem('siteMonitor.chargingVolumeToday'.tr,
            map['todayCharge'] != null ? map['todayCharge'].toString() : '--'),
      ],
    );
  }

  ///公共sn和报警
  _snAndAlarmWidget(map) {
    var alarmValue = '--';
    Color color = Colour.otherTextColor;

    if (map['alarmStatus'] != null) {
      if (map['alarmStatus'].toString() == '1') {
        alarmValue = ResKey.alarm.tr;
        color = Colour.errorTextColor;
      } else if (map['alarmStatus'].toString() == '0') {
        alarmValue = ResKey.normal.tr;
        color = Colour.green;
      }
    }
    return SizedBox(
      // height: 60 + 53,
      child: Column(
        children: [
          _nameWidget(map),
          _rowItem(ResKey.deviceSn.tr,
              map['sn'] != null ? map['sn'].toString() : '--'),
          _rowItem(ResKey.alarmStatus.tr, alarmValue, valueColor: color),
        ],
      ),
    );
  }

  ///充电枪
  _chargePileWidget(map) {
    return Column(
      children: [
        _snAndAlarmWidget(map),
        _rowItem(
            'siteMonitor.workingCondition'.tr,
            map['workStatusName'] != null
                ? map['workStatusName'].toString()
                : '--'),
        _rowItem('siteMonitor.currentPower'.tr,
            map['power'] != null ? '${map['power']}(kW)' : '--'),
      ],
    );
  }

  ///电表
  _electricityMeterWidget(map) {
    return Column(
      children: [
        _nameWidget(map),
        _rowItem(ResKey.productModel.tr,
            map['model'] != null ? map['model'].toString() : '--'),
        _rowItem(
            ResKey.electricityMeterAddress.tr,
            map['meterAddress'] != null
                ? map['meterAddress'].toString()
                : '--'),
        _rowItem('siteMonitor.totalActivePower'.tr,
            map['power'] != null ? '${map['power']}(kW)' : '--'),
      ],
    );
  }

  _nameWidget(map) {
    return SizedBox(
      height: 53,
      child: Row(
        children: [
          Expanded(
            child: Text(
              map['deviceName'] != null ? map['deviceName'].toString() : '--',
              style: TextStyle(
                  color: Colour.mainTextColor,
                  fontSize: 18.sp,
                  fontWeight: FontWeight.w500),
              overflow: TextOverflow.ellipsis,
            ),
          ),
          Padding(
              padding: EdgeInsets.only(left: 10.w),
              child: statusWidget(map['connectStatus'] != null
                  ? $enumDecodeNullable(
                      $ConnectStatusTypeEnumMap, map['connectStatus'])
                  : ConnectStatusType.off)),
        ],
      ),
    );
  }

  Widget statusWidget(ConnectStatusType? statusType) {
    Color color;
    switch (statusType) {
      case ConnectStatusType.on:
        color = const Color(0xFF00AE66);
        break;

      default:
        color = Colour.labelTextColor;
        break;
    }
    return Opacity(
      opacity: statusType == null ? 0 : 1,
      child: Container(
        alignment: Alignment.center,
        padding: EdgeInsets.symmetric(horizontal: 4.w),
        height: 22,
        decoration: BoxDecoration(
            color: color.withOpacity(0.1),
            borderRadius: BorderRadius.circular(4)),
        child: Text(
          statusType?.label ?? '',
          style: TextStyles.styleWith(12.sp, color: color),
        ),
      ),
    );
  }

  _rowItem(String title, String value,
      {Color valueColor = Colour.mainTextColor}) {
    return Container(
      margin: const EdgeInsets.only(top: 3, bottom: 3),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            width: 90.w,
            child: Text(
              title,
              style: ytTextStyle(fontSize: 14, color: Colour.lightTextColor),
            ),
          ),
          Gaps.hGap16,
          Expanded(
              child: Text(
            value,
            maxLines: 2,
            style: ytTextStyle(fontSize: 14, color: valueColor),
          )),
        ],
      ),
    );
  }
}
